<?php

namespace Icsoc\QueueBundle\Controller;

use Icsoc\CoreBundle\Controller\BaseController;
use Icsoc\CoreBundle\Export\DataType\ArrayType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\File;

/**
 * 技能组管理
 * Class QueueController
 * @package Icsoc\QueueBundle\Controller
 */
class QueueController extends BaseController
{
    const BATCH_DIR = '/var/queue/batch'; //存放批量导入的文件地址
    /**
     * 星期
     * @var array
     */
    private $week = array(0=>"周日", 1=>"周一", 2=>"周二", 3=>"周三", 4=>"周四", 5=>"周五", 6=>"周六");

    /**
     * 渲染技能组列表
     *
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $filter = $request->get('filter', '');
        $actionList = $this->getActionList();
        $actions = explode(',', $actionList);
        $isBatchAdd = ($actionList == 'all'  || in_array('icsoc_queue_batch', $actions)) ? true : false;

        return $this->render('IcsocQueueBundle:Queue:index.html.twig', array(
            'isBatchAdd'=>$isBatchAdd,
            'page' => $page,
            'rows' => $rows,
            'filter' => json_decode($filter),
        ));
    }

    /**
     * 获取技能组列表的值
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $filter = $request->get('filter', '');

        $info = array(
            'pagination'=>array('rows'=>$rows, 'page'=>$page),
            'filter'=> !empty($filter) ? json_decode($filter, true) : array(),
            'sort'=>array('order'=>$sord, 'field'=>$sidx),
        );
        $vccCode = $this->getUser()->getVccCode();
        $queType = $this->container->getParameter('que_type');
        $queStrategy = $this->container->getParameter('que_strategy');
        //权限管理
        $condtions = $this->get("icsoc_core.common.class")->getUserTypeCondition();
        if (isset($condtions['que_id']) && !empty($condtions['que_id']) && is_array($condtions['que_id'])) {
            $info['filter']['que_ids'] = implode(',', $condtions['que_id']);
        }
        $list = $this->get('icsoc_data.model.queue')->getList(
            array(
                'vcc_code'=>$vccCode,
                'info'=>json_encode($info),
            )
        );
        $data = $res = array();
        if (isset($list['data']) && !empty($list['data'])) {
            foreach ($list['data'] as $v) {
                $v['que_type'] = isset($queType[$v['que_type']]) ? $queType[$v['que_type']] : '';
                $v['que_strategy'] = isset($queStrategy[$v['que_strategy']]) ? $queStrategy[$v['que_strategy']] : '';
                $res[] = $v;

            }
        }
        $data['rows'] = $res;
        $data['page'] = $page;
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;

        return new JsonResponse($data);
    }

    /**
     * 添加技能组
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAction(Request $request)
    {
        $queForm = $this->createForm('que_info_form');
        $vccId = $this->getVccId();
        //通过企业ID获取下企业是否启用了业务组功能
        $configs = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId'=>$vccId));
        $isEnableGroup = 0;
        if (!empty($configs)) {
            $isEnableGroup = $configs->getIsEnableGroup();
        }
        if ($request->getMethod() == 'POST') {
            $arr = $request->get('que_info_form');
            $turnUp = empty($request->get('turn_up')) ? 1 : $request->get('turn_up');
            $timeConfig = array();
            if ($turnUp == 2) {
                $timeConfig['date']['type'] = empty($request->get('data_type')) ? 1 : $request->get('data_type');
                $timeConfig['date']['start_date'] = empty($request->get('start_date')) ? '*' : $request->get('start_date');
                $timeConfig['date']['end_date'] = empty($request->get('end_date')) ? '*' : $request->get('end_date');
                $having = empty($request->get('having')) ? 1 : $request->get('having');
                $math = 0;
                for ($i=1; $i <= $having; $i++) {
                    if (empty($request->get('start_time'.$i))) {
                        continue;
                    }
                    $timeConfig['time'][$math]['start_time'] = empty($request->get('start_time'.$i)) ? '' : $request->get('start_time'.$i);
                    $timeConfig['time'][$math]['end_time'] = empty($request->get('end_time'.$i)) ? '' : $request->get('end_time'.$i);
                    $timeConfig['time'][$math]['week'] = empty($request->get('weeks'.$i)) ? '' : $request->get('weeks'.$i);
                    $math++;
                }
                $soundsType = empty($request->get('sound_type')) ? 2 : $request->get('sound_type');
                $timeConfig['sound']['type'] = $soundsType;
                if ($soundsType == 2) {
                    $timeConfig['sound']['id'] = '';
                    $timeConfig['sound']['content'] = empty($request->get('tts_text')) ? '' : $request->get('tts_text');
                    $ttsRes = $this->get('icsoc_core.common.class')->getTtsSound($timeConfig['sound']['content']);
                    $timeConfig['sound']['path'] = $ttsRes['error'] === false ? $ttsRes['path'] : '';
                    if ($ttsRes['error'] === true) {
                        $message = 'tts合成失败';
                        $type = "danger";
                        goto ttsReseErrorTrue;
                    }
                } else {
                    $soundId = $request->get('sound_id');
                    $sounds = $this->get('icsoc_data.model.sound')->getTheSoundsArray($soundId);
                    $soundPath = $sounds['sounds_address'];
                    $soundPath = pathinfo($soundPath);
                    $timeConfig['sound']['id'] = $soundId;
                    $timeConfig['sound']['path'] = $soundPath['dirname'].'/'.$soundPath['filename'];
                    $timeConfig['sound']['content'] = '';
                }
                $arr['que_time_config'] = json_encode($timeConfig, JSON_UNESCAPED_SLASHES);
            } else {
                $arr['que_time_config'] = '';
            }
            $groupBelong = $request->get('group_belong', array());
            $arr['vcc_code'] = $this->getUser()->getVccCode();
            $arr['group_belong'] = $groupBelong;
            $msg = $this->get('icsoc_data.model.queue')->add($arr, $isEnableGroup);
            if (isset($msg['code']) && ($msg['code'] == 200 || ($msg['code'] == 406))) {
                if (isset($msg['code']) && $msg['code'] == 406) {
                    $msg['message'] = $this->trans('Skill set overload failure');
                } else {
                    $msg['message'] = $this->trans('Skill set overload success');
                }
                $message = $this->get('translator')->trans('Add skill group success')." [".$msg['message'].']';
                $type = "success";
            } else {
                $type = "danger";
                $message = $this->get('translator')->trans('Add skill set failure').' '.isset($msg['message'])
                    ? $msg['message'] : '';
            }
            ttsReseErrorTrue:
            $data = array(
                'data'=>array(
                    'msg_detail' => $message,
                    'type' => $type,
                    'link' => array(
                        array(
                            'text'=>$this->get('translator')->trans('Continue to add'),
                            'href'=>$this->generateUrl('icsoc_queue_add'),
                        ),
                        array(
                            'text'=> $this->get('translator')->trans('Skill list'),
                            'href'=>$this->generateUrl('icsoc_queue_index'),
                        ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        //通过企业ID获取业务组
        $groups = $this->get("icsoc_data.model.role")->getGroupDataByVccId($vccId);
        //获取语音列表
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsTypeArray($vccId, 1);

        return $this->render('IcsocQueueBundle:Queue:queInfo.html.twig', array(
                'form' => $queForm->createView(),
                'isEnableGroup' => $isEnableGroup,
                'groups' => $groups,
                'is_edit' => 0,
                'weeks' => $this->week,
                'sounds' => $sounds
            ));
    }

    /**
     * 修改技能组
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAction(Request $request)
    {
        $id = (int) $request->get('id', 0);
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $filter = $request->get('filter', '');

        $vccId = $this->getVccId();
        //通过企业ID获取下企业是否启用了业务组功能
        $configs = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId'=>$vccId));
        $isEnableGroup = 0;
        if (!empty($configs)) {
            $isEnableGroup = $configs->getIsEnableGroup();
        }
        $winQue = $this->get('doctrine.dbal.default_connection')->fetchAssoc(
            "SELECT que_name,que_type,que_strategy,brecord,que_length,que_time,ring_time,next_wait,b_announce,
            noans_times,noans_wait,noans_action,wait_audio,que_num,que_priority,tellevel,group_belong,que_time_config FROM win_queue WHERE id = :id AND vcc_id = :vcc_id",
            array('id'=>$id, 'vcc_id'=>$vccId)
        );

        // 是否自动转满意度
        $autoEvaluate = $winQue['tellevel'] & 64;
        if (empty($autoEvaluate)) {
            $winQue['auto_evaluate'] = 0;
        } else {
            $winQue['auto_evaluate'] = 1;
        }

        // 客户挂机时是否报工号
        $or = $winQue['tellevel']|32;
        $and = $winQue['tellevel']&32;
        if (empty($or) || empty($and)) {
            $winQue['tellevel'] = 0;
        } else {
            $winQue['tellevel'] = 1;
        }
        $winQue['que_id'] = $id;
        $queForm = $this->createForm('que_info_form', $winQue);
        if ($request->getMethod() == 'POST') {
            $arr = $request->get('que_info_form');
            $turnUp = empty($request->get('turn_up')) ? 1 : $request->get('turn_up');
            $timeConfig = array();
            if ($turnUp == 2) {
                $timeConfig['date']['type'] = empty($request->get('data_type')) ? 1 : $request->get('data_type');
                $timeConfig['date']['start_date'] = empty($request->get('start_date')) ? '*' : $request->get('start_date');
                $timeConfig['date']['end_date'] = empty($request->get('end_date')) ? '*' : $request->get('end_date');
                $having = empty($request->get('having')) ? 1 : $request->get('having');
                $math = 0;
                for ($i=1; $i <= $having; $i++) {
                    if (empty($request->get('start_time'.$i))) {
                        continue;
                    }
                    $timeConfig['time'][$math]['start_time'] = empty($request->get('start_time'.$i)) ? '' : $request->get('start_time'.$i);
                    $timeConfig['time'][$math]['end_time'] = empty($request->get('end_time'.$i)) ? '' : $request->get('end_time'.$i);
                    $timeConfig['time'][$math]['week'] = empty($request->get('weeks'.$i)) ? '' : $request->get('weeks'.$i);
                    $math++;
                }
                $soundsType = empty($request->get('sound_type')) ? 4 : $request->get('sound_type');
                $timeConfig['sound']['type'] = $soundsType;
                if ($soundsType == 2) {
                    $timeConfig['sound']['id'] = '';
                    $timeConfig['sound']['content'] = empty($request->get('tts_text')) ? '' : $request->get('tts_text');
                    $ttsRes = $this->get('icsoc_core.common.class')->getTtsSound($timeConfig['sound']['content']);
                    $timeConfig['sound']['path'] = $ttsRes['error'] === false ? $ttsRes['path'] : '';
                    if ($ttsRes['error'] === true) {
                        $message = 'tts合成失败';
                        $type = "danger";
                        goto ttsReseErrorTrue;
                    }
                } else {
                    $soundId = $request->get('sound_id');
                    $sounds = $this->get('icsoc_data.model.sound')->getTheSoundsArray($soundId);
                    $soundPath = $sounds['sounds_address'];
                    $soundPath = pathinfo($soundPath);
                    $timeConfig['sound']['id'] = $soundId;
                    $timeConfig['sound']['path'] = $soundPath['dirname'].'/'.$soundPath['filename'];
                    $timeConfig['sound']['content'] = '';
                }
                $arr['que_time_config'] = json_encode($timeConfig, JSON_UNESCAPED_SLASHES);
            } else {
                $arr['que_time_config'] = '';
            }
            $groupBelong = $request->get('group_belong', array());
            $arr['vcc_code'] = $this->getUser()->getVccCode();
            $arr['group_belong'] = $groupBelong;
            $msg = $this->get('icsoc_data.model.queue')->update($arr, $isEnableGroup);
            if (isset($msg['code']) && ($msg['code'] == 200 || ($msg['code'] == 407))) {
                if (isset($msg['code']) && $msg['code'] == 407) {
                    $message = $this->trans('Skill set overload failure');
                } else {
                    $message = $this->trans('Skill set overload success');
                }
                $type = "success";
            } else {
                $type = "danger";
                $message = $this->get('translator')->trans("Update skill set failure").' ';
                $message.= isset($msg['message'])
                    ? $msg['message'] : '';
            }
            ttsReseErrorTrue:
            $data = array(
                'data'=>array(
                    'msg_detail' => $message,
                    'type' => $type,
                    'link' => array(
                        array(
                            'text'=>$this->get('translator')->trans('Skill list'),
                            'href'=>$this->generateUrl('icsoc_queue_index', array('page'=>$page, 'rows'=>$rows, 'filter'=>$filter)),
                        ),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }
        //通过企业ID获取业务组
        $groups = $this->get("icsoc_data.model.role")->getGroupDataByVccId($vccId);
        $newgroupbelong = "";
        if (!empty($winQue['group_belong'])) {
            $newgroupbelong = explode(",", $winQue['group_belong']);
        }

        $timeConfig = '';
        $timeUp = 1;
        if (!empty($winQue['que_time_config'])) {
            $timeConfig = json_decode($winQue['que_time_config']);
            $timeUp = 2;
        }
        //获取语音列表
        $sounds = $this->get('icsoc_data.model.sound')->getSoundsTypeArray($vccId, 1);

        return $this->render('IcsocQueueBundle:Queue:editque.html.twig', array(
                'form' => $queForm->createView(),
                'id'=>$id,
                'isEnableGroup' => $isEnableGroup,
                'groups' => $groups,
                'newgroupbelong' => $newgroupbelong,
                'is_edit' => 1,
                'timeUp' => $timeUp,
                'dataType' => empty($timeConfig->date->type) ? 1 : $timeConfig->date->type,
                'startDate' => empty($timeConfig->date->start_date) ? '' : $timeConfig->date->start_date,
                'endDate' => empty($timeConfig->date->end_date) ? '' : $timeConfig->date->end_date,
                'weeks' => $this->week,
                'timeData' => empty($timeConfig->time) ? '' : $timeConfig->time,
                'soundType' => empty($timeConfig->sound->type) ? 2 : $timeConfig->sound->type,
                'soundId' => empty($timeConfig->sound->id) ? '' : $timeConfig->sound->id,
                'content' => empty($timeConfig->sound->content) ? '' : $timeConfig->sound->content,
                'sounds' => $sounds,
                'page' => $page,
                'rows' => $rows,
                'filter' => $filter,
            ));
    }

    /**
     * 删除技能组
     * @param Request $request
     * @return JsonResponse
     */
    public function delAction(Request $request)
    {
        $id = $request->get('id', 0);
        $arr['que_id'] = $id;
        $arr['flag'] = 0; //需要验证是否有坐席；
        $arr['vcc_code'] = $this->getUser()->getVccCode();
        $arr['flag'] = 1;
        $msg = $this->get('icsoc_data.model.queue')->delQue($arr);
        $success = array();
        $error = array() ;
        foreach ($msg['data'] as $value) {
            if (isset($value['code']) && ($value['code'] == 200)) {
                $success[] = $value['que_id'];
            } else {
                $message = $value['code'] == 406 ? $this->trans('Overloading failure') : $value['message'];
                $error[] = $value['que_id'].':'.$message.' &nbsp;&nbsp;';
            }
        }
        $message = $this->trans('Delete fail').'['.implode(',', $error)."] <br/>";
        $message.= $this->trans('Delete success').'['.implode(',', $success).'] <br/>';
//        $message.= $this->trans('Successfully deleted, overloading failure').'['.implode(',', $reload).'] ';
        return new JsonResponse(array('message'=>$message, 'error'=>false));
    }


    /**
     * 检测技能组是否存在
     * @param Request $request
     * @return Response
     */
    public function checkAction(Request $request)
    {
        $queName = $request->get('que_name');
        $queId = $request->get('que_id');
        $queType = $request->get('que_type', ''); //区分是技能组号还是技能组名称
        //技能组名称重复
        $vid = $this->getUser()->getVccId();
        $where = " vcc_id = :vcc_id AND id <> :que_id AND is_del = 0";
        $parArr = array('vcc_id'=>$vid, 'que_id' => $queId);
        if ($queType == 1) {
            if ($queName == 0) {
                return new Response("true");
            }
            $where.=" AND que_num = :que_num ";
            $parArr['que_num'] = $queName;
        } else {
            $where.=" AND que_name = :que_name ";
            $parArr['que_name'] = $queName;
        }
        $msg = $this->container->get('icsoc_data.validator')->existQue($where, $parArr);
        if (!empty($msg) && is_array($msg)) {
            return new Response("false");
        }

        return new Response("true");
    }

    /**
     * 获取技能组下的坐席信息
     * @param Request $request
     * @return JsonResponse
     */
    public function getDistributionAction(Request $request)
    {
        $vccCode = $this->getUser()->getVccCode();
        $queId = $request->get('que_id');
        $arr = array('vcc_code'=>$vccCode, 'que_id'=>$queId);
        $msg = $this->get('icsoc_data.model.agent')->listAgent($arr);
        $data = array();
        if (isset($msg['code']) && $msg['code'] == 200) {
            $keys = array();
            foreach ($msg['data'] as $val) {
                $keys[] = $val['ag_id'];
            }
            $data['que_agent'] = $msg['data'];
            //获取所有的坐席
            $list = $this->get('icsoc_data.model.agent')->listAgent(array('vcc_code'=>$vccCode));
            $newList = array();
            foreach ($list['data'] as $val) {
                if (!in_array($val['ag_id'], $keys)) {
                    $newList[] = $val;
                }
            }
            $data['list_agent'] = $newList;
            $data['error'] = 0;
        } else {
            $data['error'] = 1;
            $data['message'] = $msg['message'];
        }

        return new JsonResponse($data);
    }

    /**
     * 设置 分配技能组的坐席
     * @param Request $request
     * @return Response
     */
    public function setDistributionAction(Request $request)
    {
        $vccCode = $this->getUser()->getVccCode();
        $queId = $request->get('que_id');
        $agents = $request->get('agents');
        //先取消所有；
        $param = array('vcc_code'=>$vccCode, 'que_id'=>$queId);
        $res = $this->get('icsoc_data.model.agent')->listAgent($param);
        $keys = array();
        foreach ($res['data'] as $val) {
            $keys[] = $val['ag_id'];
        }
        $param['agents'] = json_encode($keys);
        $this->get('icsoc_data.model.queue')->cancelAssign($param);
        $param['agents'] = $agents;
        //错误的情况暂且不知道怎么提示；
        $msg = $this->get('icsoc_data.model.queue')->assignQueAgent($param);
        if ($msg['code'] == 500) {
            return new JsonResponse(array('error'=>0));
        } else {
            return new JsonResponse(array('error'=>1, 'message'=>$msg['message']));
        }
    }

    /**
     * 快捷分配
     * @param Request $request
     * @return JsonResponse
     */
    public function setFastDistributionAction(Request $request)
    {
        $conn = $this->get('doctrine.dbal.default_connection');
        $vccCode = $this->getVccCode();
        $vccId = $this->getVccId();
        $queId = $request->get('que_id', '');
        $agents = $request->get('agents', '');
        $agents = explode(',', $agents);
        $param = array('vcc_code'=>$vccCode, 'que_id'=>$queId);
        $res = $this->get('icsoc_data.model.agent')->listAgent($param);
        $keys = array();
        foreach ($res['data'] as $val) {
            $keys[] = $val['ag_id'];
        }
        $del = array_diff($agents, $keys); //删除
        $add = array_diff($keys, $agents); //新增
        $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
        //$address = $this->getUser()->getWinIp();
        $port = $this->container->getParameter('win_socket_port');
        $message = array();
        if (!empty($del)) {
            foreach ($del as $v) {
                //$conn->beginTransaction();
                $conn->delete('win_agqu', array('que_id'=>$queId, 'ag_id'=>$v));
                //重载坐席
                $resMeesg = $this->get('icsoc_data.validator')->reloadAgent($vccId, $address, $v, $port);
                if (isset($resMeesg['code']) && $resMeesg['code'] != 200) {
                    //$conn->rollBack();
                    $agNum = $conn->fetchColumn("SELECT ag_num FROM win_agent WHERE id = :id", array('id'=>$v));
                    $message[] = $agNum;
                } else {
                   // $conn->commit();
                }
            }
        }
        if (!empty($add)) {
            foreach ($add as $v) {
                //$conn->beginTransaction();
                $conn->insert('win_agqu', array('que_id'=>$queId, 'ag_id'=>$v));
                //重载坐席
                $resMeesg = $this->get('icsoc_data.validator')->reloadAgent($vccId, $address, $v, $port);
                if (isset($resMeesg['code']) && $resMeesg['code'] != 200) {
                    //$conn->rollBack();
                    $agNum = $conn->fetchColumn("SELECT ag_num FROM win_agent WHERE id = :id", array('id'=>$v));
                    $message[] = $agNum;
                } else {
                    //$conn->commit();
                }
            }
        }
        $agentStr = $this->get('translator')->trans('Agent number')."[".implode(',', $message)."]";
        $agentStr.= $this->get('translator')->trans('Allocation failure');
        $str = !empty($message) ? $agentStr : $this->get('translator')->trans('The distribution of success');

        return new JsonResponse(array('message'=>$str, 'error'=>!empty($message) ? 1 : 0 ));
    }

    /**
     * 渲染页面
     * @param Request $request
     * @return Response
     */
    public function agquAction(Request $request)
    {
        $queId = $request->get("que_id", '');
        $em = $this->getDoctrine()->getManager();
        $vccId = $this->getUser()->getVccId();
        //技能组
        $queues = $em->getRepository('IcsocSecurityBundle:WinQueue')
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId'=>$vccId));
        if (empty($queId) && !empty($queues)) {
            $queId = array_keys($queues); //默认给第一个;
            $queId = $queId[0];
        }

        return $this->render("IcsocQueueBundle:Queue:agqu.html.twig", array(
                'queues'=>$queues,
                'que_id'=>$queId,
            ));
    }

    /**
     * 修改技能水平
     * @param Request $request
     * @return JsonResponse
     */
    public function updateSkillAction(Request $request)
    {
        //$id = $request->get('id', 0);
        //$val = $request->get('val', 0);
        $id = $request->get('aqid', 0);
        $val = (int) $request->get('skill', 0);
        $em = $this->getDoctrine()->getManager();
        /** @var \Icsoc\SecurityBundle\Entity\WinAgqu $agQu */
        $agQu = $em->getRepository("IcsocSecurityBundle:WinAgqu")->find($id);
        if (!empty($agQu)) {
            $agQu->setSkill($val);
            $em->flush();

            return new JsonResponse(array('error'=>0));
        }

        return new JsonResponse(array('error'=>1));
    }

    /**
     * 获取某一技能组未分配的坐席
     * @param Request $request
     * @return JsonResponse
     */
    public function getAgentAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $queId = $request->get('que_id');
        $queIds = $request->get('que_ids', '');
        $keyword = $request->get("keyword", '');
        $queId = empty($queIds) ? $queId : $queIds;
        $data = array();
        if (!empty($queId)) {
            $arr = array('vcc_code'=>$vccCode, 'que_id'=>$queId, 'ag_role'=>true, 'info'=>json_encode(array(
                'pagination'=>array('rows'=>10000)
            )));
            //查询已经分配的坐席
            $msg = $this->get('icsoc_data.model.agent')->listAgent($arr);
            if (isset($msg['code']) && $msg['code'] == 200) {
                $keys = array();
                foreach ($msg['data'] as $val) {
                    $keys[] = $val['ag_id'];
                }
                //获取所有的坐席
                $arr = array('vcc_code'=>$vccCode, 'ag_role'=>true, 'info'=>json_encode(array(
                    'pagination'=>array('rows'=>10000)
                )));
                if (!empty($keyword)) {
                    $arr['info'] = json_encode(array('filter'=>array('assign_keyword'=>$keyword)));
                }
                $list = $this->get('icsoc_data.model.agent')->listAgent($arr);
                foreach ($list['data'] as $val) {
                    if (!in_array($val['ag_id'], $keys)) {
                        $data[] = $val;
                    }
                }
            }
        }

        return new JsonResponse(array('rows'=>$data));
    }

    /**
     * 获取已经分配了的坐席
     * @param Request $request
     * @return JsonResponse
     */
    public function getAssignAgentAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $queId = $request->get('que_id');
        $queIds = $request->get('que_ids');
        $keyword = $request->get("keyword", '');
        $queId = empty($queIds) ? $queId : $queIds;
        $data = array();
        if (!empty($queId)) {
            $arr = array('vcc_code'=>$vccCode, 'que_id'=>$queId, 'ag_role'=>true);
            $arr['info'] = json_encode(array('filter'=>array('assign_keyword'=>$keyword)));
            $msg = $this->get('icsoc_data.model.agent')->listAgent($arr);
            if (isset($msg['code']) && $msg['code'] == 200) {
                $data = $msg['data'];
            }
        }

        return new JsonResponse(array('rows'=>$data));
    }

    /**
     * 分配坐席
     * @param Request $request
     * @return JsonResponse
     */
    public function setAssignAgentAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $queId = $request->get('que_id', '');
        $param = array('vcc_code'=>$vccCode, 'que_id'=>$queId);
        $ids = $request->get("ids", '');
        $ids = explode(",", $ids);
        $agents = array();
        foreach ($ids as $val) {
            $agents[] = array('ag_id'=>$val, 'skill'=>1);
        }
        $param['agents'] = json_encode($agents);
        $msg = $this->get('icsoc_data.model.queue')->assignQueAgent($param);
        if ($msg['code'] == 500) {
            $success = $fail = '[';
            foreach ($msg['data'] as $message) {
                if ($message['code'] == 200) {
                    $success.=$message['data']['ag_id'].',';
                } else {
                    $fail.=$message['data']['ag_id'].',';
                }
            }

            return new JsonResponse(
                array(
                    'error'=>0,
                     $this->trans('success').$success.'] '.$this->trans('fail').$fail.']',
                )
            );
        } else {
            return new JsonResponse(array('error'=>1, 'message'=>$msg['message']));
        }
    }

    /**
     * 取消分配；
     * @param Request $request
     * @return JsonResponse
     */
    public function cancelAssignAgentAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $queId = $request->get('que_id', '');
        $param = array('vcc_code'=>$vccCode, 'que_id'=>$queId);
        $ids = $request->get("ids", '');
        $ids = explode(",", $ids);
        $param['agents'] = json_encode($ids);
        $msg = $this->get('icsoc_data.model.queue')->cancelAssign($param);
        if ($msg['code'] == 200) {
            return new JsonResponse(array('error'=>0));
        }

        return new JsonResponse(array('error'=>1, 'message'=>$msg['messsage']));
    }

    /**
     * 设置快捷分配；
     * @param Request $request
     * @return JsonResponse
     */
    public function fastAssignAgentAction(Request $request)
    {
        $vccCode = $this->getVccCode();
        $queId = $request->get('que_id', '');
        $flag = $request->get('flag', 1); //标识是添加还是删除；
        $param = array('vcc_code'=>$vccCode, 'que_id'=>$queId, 'flag'=>$flag);
        $ids = $request->get("ids", '');
        $ids = explode(",", $ids);
        $param['ids'] = $ids;
        $msg = $this->get('icsoc_data.model.queue')->actionFastAssignAgent($param);
        if ($msg['code'] == 200) {
            return new JsonResponse(array('error'=>0));
        }

        return new JsonResponse(array('error'=>1, 'message'=>$msg['message']));
    }

    /**
     * 批量添加技能组页面
     * @return Response
     */
    public function batchAddAction()
    {
        return $this->render("IcsocQueueBundle:Queue:queueBatch.html.twig");
    }

    /**
     * 导出批量添加模板
     */
    public function exportAction()
    {
        /* 文件头 */
        $filed = array(
            'que_name'=>array('name'=>$this->trans('Skill group name')),
            'que_num'=>array('name'=>$this->trans('Skill group number')),
            'que_type'=>array('name'=>$this->trans('The skill set of type')),
            'que_time'=>array('name'=>$this->trans('The queue length')),
            'ring_time'=>array('name'=>$this->trans('Seat ringing duration')),
            'next_wait'=>array('name'=>$this->trans('Post processing time')),
            'b_announce'=>array('name'=>$this->trans('Whether the reported number')),
            'tellevel'=>array('name'=>$this->trans('Custom hangup Whether the reported number')),
            'que_priority'=>array('name'=>$this->trans('The skill set priority')),
            'if_login'=>array('name'=>$this->trans('if static login')),
            'agent_phone'=>array('name'=>$this->trans('agent1 phone')),
            'agent_agqu'=>array('name'=>$this->trans('agent1 skill level')),
            'agent_role'=>array('name'=>$this->trans('agent1 role')),
        );
        $source = new ArrayType(array(), $filed);
        $this->get('icsoc_core.export.csv')->export($source);
    }

    /**
     * 将文件上传到服务器；
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function uploadAction(Request $request)
    {
        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
        $file = $request->files->get('file_address');
        $valiFile = new File();
        $valiFile->mimeTypes = array('text/comma-separated-values', 'text/plain');
        $valiFile->mimeTypesMessage = $this->trans("The file type is only for %str%", array('%str%'=>'csv,txt'));
        $errorList = $this->container->get("validator")->validateValue($file, $valiFile);
        if (count($errorList) > 0) {
            $data = array(
                'data'=>array(
                    'msg_detail' => $this->trans(
                        'Failed to upload file %str%',
                        array('%str%'=>$errorList[0]->getMessage())
                    ),
                    'type'=>'danger',
                    'link' => array(
                        array('text'=>$this->trans('return'), 'href'=>"javascript:window.history.go(-1)"),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        $fileName = time().mt_rand().'.csv';
        $targetPath = self::BATCH_DIR.'/'.$fileName;
        $stream = fopen($file->getPathname(), 'r');
        $alioss = $this->container->get("icsoc_filesystem")->putStream($targetPath, $stream);
        if (!$alioss) {
            $data = array(
                'data'=>array(
                    'msg_detail' => $this->trans('Failed to upload file %str%', array('%str%'=>'写入到flsystem失败')),
                    'type'=>'danger',
                    'link' => array(
                        array('text'=>$this->trans('return'), 'href'=>"javascript:window.history.go(-1)"),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render("IcsocQueueBundle:Queue:queueBatchUpload.html.twig", array(
            'file'=>$fileName,
            'flag'=>$this->trans('loading...'),
        ));
    }

    /**
     * 读取导入的数据并验证；
     * @param Request $request
     * @return JsonResponse
     */
    public function uploadDataAction(Request $request)
    {
        $ruleInt = "/^[0-9]*[1-9][0-9]*$/";//正整数
        $rulePhone1 = "/^(4|8)00[0-9]{7}$/";//400号(10位)
        $rulePhone2 = "/^1010[0-9]{4}$/";//1010号(8位)
        $rulePhone3 = "/^(010|(02[0-9])|(0[3-9][0-9]{2}))[0-9]{7,8}$/";//区号+固话
        $rulePhone4 = "/^(10|(2[0-9])|([3-9][0-9]{2}))[0-9]{7,8}$/";//少掉0的区号+固话
        $ruleMobile1 = "/^01[3-9]\d{9}$/";//手机号码加0
        $ruleMobile2 = "/^1[3-9]\d{9}$/";//手机号码
        $vccId = $this->getVccId();
        $vccCode = $this->getVccCode();
        $file = $request->get('file', '');

        $flySys = $this->container->get("icsoc_filesystem");
        $fileName = self::BATCH_DIR.'/'.$file;
        try {
            $stream = $flySys->readStream($fileName);
            $data = $this->get('icsoc_core.export.csv')->readcsv($stream);
            unset($data[0]);

            /* 取得所有技能组号 */
            $queues = array();
            $queuewName = array();
            $res = $this->container->get("doctrine.dbal.default_connection")->fetchAll(
                "SELECT id,que_name,que_num FROM win_queue WHERE vcc_id=".$vccId." AND is_del=0"
            );
            foreach ($res as $que) {
                $queues[$que['id']] = $que['que_num'];
                $queuewName[] = $que['que_name'];
            }
            $queues = array_filter($queues);
            /*取得所有分机号*/
            $phones = array();
            $phoNums = $this->container->get("doctrine.dbal.default_connection")->fetchAll(
                "SELECT id,pho_num FROM win_phone WHERE vcc_id=".$vccId
            );
            foreach ($phoNums as $nums) {
                $phones[$nums['id']] = $nums['pho_num'];
            }
            /* 取得所有角色列表 */
            $roles = array();
            $result = $this->container->get("doctrine.dbal.default_connection")->fetchAll(
                "SELECT role_id,name FROM cc_roles WHERE vcc_id=".$vccId
            );
            foreach ($result as $role) {
                $roles[$role['name']] = $role['role_id'];
            }

            $batch = array();
            $flagQueueArray = array();
            $flagQueueNameArray = array();
            $flagPhoneArray = array();
            $flagAgentNum = array();
            foreach ($data as $key => $val) {
                //判断技能组名是否不为空
                $val[0] = $this->get('icsoc_core.export.csv')->convertCharset($val[0], 'GB2312', 'UTF-8');
                if (!isset($val[0]) || $val[0] == '') {
                    return new JsonResponse(array('error'=>1, 'message'=>'技能组名称不能为空'));
                } elseif (in_array($val[0], $queuewName, true) || in_array($val[0], $flagQueueNameArray, true)) {
                    return new JsonResponse(array('error'=>1, 'message'=>'技能组名称【'.$val[0].'】与数据库或文件中其他数据重复'));
                } else {
                    $flagQueueNameArray[] = $val[0];
                }
                //$this->get("logger")->error($val[0]."xxxx技能组".json_encode($data));
                //判断技能组号是否有重复(数据库、文件)
                if (!isset($val[1]) || $val[1] == '') {
                    return new JsonResponse(array('error'=>1, 'message'=>'技能组号不能为空'));
                } elseif (!preg_match("/^[0-9]+$/", $val[1])) {
                    return new JsonResponse(array('error'=>1, 'message'=>'技能组号只能填数字'));
                } elseif (in_array($val[1], $queues, true) || in_array($val[1], $flagQueueArray, true)) {
                    return new JsonResponse(array('error'=>1, 'message'=>'技能组号【'.$val[1].'】与数据库或文件中其他数据重复'));
                } else {
                    $flagQueueArray[] = $val[1];
                }
                //技能组类型只能填0、1、2，不填默认为1（0呼入呼出 1呼入 2呼出）
                if (!isset($val[2]) || $val[2] == '') {
                    $val[2] = 1;
                } elseif (!preg_match("/^[0-2]$/", $val[2])) {
                    return new JsonResponse(array('error'=>1, 'message'=>'技能组类型只能填0、1、2，不填默认为1'));
                }
                //排队时长只能填正整数，不填默认120
                if (!isset($val[3]) || $val[3] == '') {
                    $val[3] = 120;
                } elseif (!preg_match($ruleInt, $val[3])) {
                    return new JsonResponse(array('error'=>1, 'message'=>'排队时长只能填正整数'));
                }
                //振铃时长只能填正整数，不填默认30
                if (!isset($val[4]) || $val[4] == '') {
                    $val[4] = 30;
                } elseif (!preg_match($ruleInt, $val[4])) {
                    return new JsonResponse(array('error'=>1, 'message'=>'振铃时长只能填正整数'));
                }
                //事后处理时长只能填正整数，不填默认5
                if (!isset($val[5]) || $val[5] == '') {
                    $val[5] = 5;
                } elseif (!preg_match($ruleInt, $val[5])) {
                    return new JsonResponse(array('error'=>1, 'message'=>'事后处理时长只能填正整数'));
                }
                //是否报工号只能填Y或N，不填默认N
                if (!isset($val[6]) || $val[6] == '') {
                    $val[6] = 0;
                } elseif ($val[6] == 'Y') {
                    $val[6] = 1;
                } elseif ($val[6] == 'N') {
                    $val[6] = 0;
                } else {
                    return new JsonResponse(array('error'=>1, 'message'=>'是否报工号只能填 Y 或 N'));
                }
                //是否来电播报
                if (!isset($val[7]) || $val[7] == '') {
                    $val[7] = 'N';
                } elseif (!in_array($val[7], array('Y', 'N'))) {
                    return new JsonResponse(array('error'=>1, 'message'=>'客户挂机时是否需要播报号码只能填 Y 或 N'));
                }
                //技能组优先级
                if (isset($val[8]) && $val[8] != '') {
                    if (!preg_match($ruleInt, $val[8])) {
                        return new JsonResponse(array('error'=>1, 'message'=>'技能组优先级只能填正整数'));
                    }
                } else {
                    $val[8] = 0;
                }
                $batch[$key]['queue'] = array(
                    'que_name' => $val[0],
                    'que_num' => $val[1],
                    'que_type' => $val[2],
                    'que_time' => $val[3],
                    'ring_time' => $val[4],
                    'next_wait' => $val[5],
                    'b_announce' => $val[6],
                    'tellevel' => $val[7],
                    'que_priority' => $val[8],
                );

                //判断静态登录列是否为空，不为空则判断相应坐席信息是否不为空，都不为空则判断分机号是否重复
                if (isset($val[9]) && $val[9] != '') {
                    $batch[$key]['if_login'] = $val[9];
                    if ($val[9] == 'Y' || $val[9] == 'N') {
                        if ((count($val) < 13) || !is_int((count($val) - 13) / 3)) {
                            return new JsonResponse(array('error'=>1, 'message'=>'列数不对，添加的坐席分机号、技能组水平、角色三列都必填'));
                        }
                        if (!isset($val[10]) || $val[10] == '') {
                            return new JsonResponse(array('error'=>1, 'message'=>'配置是否静态登录列后，后面坐席1的分机号、技能组水平、角色三列必填'));
                        }

                        for ($i=0; $i <= ((count($val)-13)/3); $i++) {
                            $userPhone = isset($val[10+($i*3)]) ? $val[10+($i*3)] : '';
                            $userSkill = isset($val[11+($i*3)]) ? $val[11+($i*3)] : '';
                            $userRole = isset($val[12+($i*3)]) ? $val[12+($i*3)] : '';

                            if ($userPhone != '') {
                                if (empty($userSkill) || empty($userRole)) {
                                    return new JsonResponse(array('error'=>1, 'message'=>'坐席的分机号、技能组水平、角色三列必填'));
                                } else {
                                    //坐席分机号验证
                                    if (!preg_match($rulePhone1, $userPhone) && !preg_match($rulePhone2, $userPhone) && !preg_match($ruleMobile1, $userPhone) && !preg_match($rulePhone3, $userPhone)) {
                                        if (preg_match($ruleMobile2, $userPhone) || preg_match($rulePhone4, $userPhone)) {
                                            $userPhone = '0'.$userPhone;
                                        } else {
                                            return new JsonResponse(
                                                array(
                                                    'error'=>1,
                                                    'message'=>'分机号【'.$userPhone.'】填写不正确，坐席分机号可填手机号、400号、800号、1010号、固话(固话必须填上区号)',
                                                )
                                            );
                                        }

                                    }
                                    if (in_array($userPhone, $phones) || in_array($userPhone, $flagQueueArray)) {
                                        return new JsonResponse(
                                            array(
                                                'error'=>1,
                                                'message'=>'分机号【'.$userPhone.'】与数据库或文件中其他数据重复',
                                            )
                                        );

                                    }

                                    //判断坐席技能组水平是否正整数
                                    if (!preg_match($ruleInt, $userSkill)) {
                                        return new JsonResponse(array('error'=>1, 'message'=>'坐席技能组水平只能填正整数'));
                                    } else {
                                        $flagPhoneArray[] = $userPhone;
                                        $flagAgentNum[] = $val[1].($i + 1);//员工工号
                                        $batch[$key]['agent'][] = array(
                                            'phone'=>trim($userPhone),
                                            'skill'=>$userSkill,
                                            'role'=>$userRole,
                                        );
                                    }
                                }
                            }
                        }
                    } else {
                        return new JsonResponse(array('error'=>1, 'message'=>'是否静态登录列只能填 Y 或 N'));
                    }
                } else {
                    $batch[$key]['if_login'] = '';
                }

            }
            $batch['vcc_id'] = $vccId;
            $batch['vcc_code'] = $vccCode;
            $batch['role'] = $roles;

            //判断工号是否重复
            if (!empty($flagAgentNum)) {
                $total = $this->container->get("doctrine.dbal.default_connection")->fetchColumn(
                    "SELECT COUNT(*) AS nums
                    FROM win_agent
                    WHERE vcc_id=".$vccId." AND ag_num IN('".implode("','", $flagAgentNum)."') AND is_del=0"
                );
                if ($total > 0) {
                    return new JsonResponse(array('error'=>1, 'message'=>'坐席工号(技能组号+第几个)会与数据库中工号重复'));
                }
            }
            $flySys->delete($fileName);
            $result = $this->get("icsoc_data.model.queue")->batchAddQueue($batch);
            if (isset($result['code']) && $result['code'] == 200) {
                return new JsonResponse(array('error'=>0));
            } else {
                return new JsonResponse(
                    array(
                        'error'=>1,
                        'message'=>$result['message'],
                    )
                );
            }
        } catch (\Exception $e) {
            $this->get('logger')->error($e->getMessage());

            return new JsonResponse(array('error'=>1, 'message'=>$this->trans('Upload the file does not exist')));
        }
    }
}
